package com.platform.drools.service;

import com.platform.drools.entity.Calculation;
import com.platform.drools.entity.Person;
import lombok.extern.slf4j.Slf4j;
import org.kie.api.KieBase;
import org.kie.api.KieServices;
import org.kie.api.command.Command;
import org.kie.api.command.KieCommands;
import org.kie.api.runtime.ExecutionResults;
import org.kie.api.runtime.KieContainer;
import org.kie.api.runtime.KieSession;
import org.kie.api.runtime.StatelessKieSession;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Service
@Slf4j
public class TestService {

    @Resource
    private KieSession kieSession;

    public void testService01() {
        try {
            Person p = new Person();
            p.setName("张三");
            kieSession.insert(p);
            int ruleFiredCount = kieSession.fireAllRules();
            log.info("ruleFiredCount：" + ruleFiredCount);
            kieSession.dispose();
        } catch (Exception e) {
            log.error("异常：{}", e);
        } finally {
            log.info("结束");
        }
    }

    public void calculation001() {
        try {
            log.info("开始");
            Calculation cal = new Calculation(10000);//输入当月工资
            KieServices kieServices = KieServices.get();
            KieContainer kieContainer = kieServices.getKieClasspathContainer();
//        KieSession kieSession = kieContainer.newKieSession("ksession-flagleader");
            KieBase kieBase = kieContainer.getKieBase("calculation");
            StatelessKieSession kieSession = kieBase.newStatelessKieSession();
//            kieSession.setGlobal("cal", cal);
//            kieSession.insert(cal);
//            int ruleFiredCount = kieSession.fireAllRules();
//            log.info("ruleFiredCount：" + ruleFiredCount);
            KieCommands kieCommands = kieServices.getCommands();
            List<Command> cmds = new ArrayList<>();
            cmds.add(kieCommands.newSetGlobal("cal", cal));
            cmds.add(kieCommands.newInsert(new Person("张三", 102), "person"));
            ExecutionResults results = kieSession.execute(kieCommands.newBatchExecution(cmds));
            System.out.println(cal.toString());
            cal = (Calculation) results.getFactHandle("cal");
            Person p = (Person) results.getFactHandle("person");
            log.info("results:" + cal.toString());
            System.out.println("p:" + p.toString());
        } catch (Exception e) {
            log.error("异常：{}", e);
        } finally {
            log.info("结束");
        }
    }

}
